<?php
namespace app\common\model;
use think\Model;

/**
 * 需求模块
 */
class Need extends Model {
	protected $insert = ['add_time'];

    protected function setAddTimeAttr(){
        return time();
    }


    //地图需求列表
    public function needByMap($where = [],$lng = '',$lat = '',$having = ''){
        $list = $this->alias('n')->join(['bz_user' => 'u'],'u.id = n.user_id')
            ->where('n.status',1)->where('end_time','egt',time())->where($where)
            ->field("n.id,u.id as user_id,nick_name,photo_path,age,sex,zhiye,kaopu,service_count,lng,lat,FROM_UNIXTIME(end_time,'%Y-%m-%d %H:%i') as format_time,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( $lat * PI() / 180 - lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * POW(SIN(($lng * PI() / 180 - lng * PI() / 180) / 2),2)))) AS juli")
            ->having($having)
            ->select();
         
        $zhiye = db('zhiye');
        foreach($list as $key => $val){
            $list[$key]['zhiye'] = $val['zhiye'] == 0?'':$zhiye->where('id',$val['zhiye'])->value('name');
        }
        return $list;
    }

    /**
     * [getInfo 需求详情]
     * @param  array  $where [description]
     * @param  string $lng   [当前用户经度]
     * @param  string $lat   [当前用户纬度]
     * @return [type]        [description]
     */
    public function getInfo($where=[],$lng = '',$lat = ''){

        $info = $this->alias('n')->join(['bz_user'=>'u'],'u.id = n.user_id')->where($where)->where('n.status',1)->field('n.*,u.id as user_id,photo_path,nick_name,kaopu,service_count,sex,tag,FROM_UNIXTIME(end_time,"%Y-%m-%d %H:%i") as end_time')->find();

        if(is_null($info)){
            return $info;
        }

        //图片
        if($info['image']){
            $info['image'] = explode(',',$info['image']);
        }else{
            $info['image'] = [];
        }

        //会员标签
        if($info['tag']){
            $info['tag'] = explode(',',$info['tag']);
        }else{
            $info['tag'] = [];
        }

        //距离该发布者距离
        $info['juli'] = round(get_distance($lat,$lng,$info['lat'],$info['lng'])/1000,4);

        
        //申请者列表
        $info['applyer'] = $this->applyer($info['id']);

        return $info;
    }


    /**
     * [applyer 需求申请者列表]
     * @return [type] [description]
     */
    public function applyer($id,$p=0){
        $model = db('need_apply')->alias('a')->join(['bz_user'=>'u'],'u.id = a.apply_user','left')->field('u.id as user_id,photo_path,nick_name')->where('foreign_key',$id);
        if($p > 0){
            $model->limit(($p-1)*config('page_size'),config('page_size'));
        }else{
            $model->limit(5);
        }
        $list = $model->order('a.id desc')->select();
        foreach($list as $key => $val){
            if($val['photo_path'] && strpos($val['photo_path'],'http') === false){
                $list[$key]['photo_path'] = config('http_server').$val['photo_path'];
            }
        }
        return  empty($list)?[]:$list;
    }


    /**
     * [needList 需求列表 默认显示最近的地点]
     * @param  array   $where [description]
     * @param  string  $order [根据距离排序]
     * @param  integer $p     [当前页码]
     * @param  string  $lng   [当前用户经度]
     * @param  string  $lat   [当前用户纬度]
     * @return [type]         [description]
     */
    public function needList($where = [],$order = 'n.add_time desc',$p = 0 ,$lng = '',$lat = '',$page_size = 0){
        if($page_size == 0){
            $page_size = config('page_size');
        }

        $field = "n.*,n.id as need_id,nick_name,photo_path,sex,kaopu,service_count,zhiye";
        if($lng !== '' && $lng !== ''){
            $field .= ",ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( $lat * PI() / 180 - lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * POW(SIN(($lng * PI() / 180 - lng * PI() / 180) / 2),2)))) AS juli";
        }

        $this->alias('n')->join(['bz_user'=>'u'],'n.user_id = u.id')
            ->where($where)->where('n.status',1)
            ->field($field)
            ->order($order)
            ->group('need_id');
           
        if($p > 0){
            $this->limit(($p-1)*$page_size,$page_size);
        }
        $list = $this->select();


        return $list;
    }
    

    /**
     * [dataCheck 数据处理]
     * @param  array   $list    [数据列表]
     * @param  integer $user_id [当前会员id]
     * @return [type]           [description]
     */
    public function dataCheck($list = [] ,$user_id = 0){
        $orderModel = db('need_apply');
        $zhiyeModel = db('zhiye');
        foreach($list as $key => $val){
            $list[$key]['image'] = empty($val['image'])?[]:explode(',',$val['image']);
            $list[$key]['format_time'] = timeFormat($val['add_time']);
            //需求状态
            $list[$key]['status'] = $val['end_time'] > time() ? 1 : 0 ;
            if(isset($val['photo_path']) && $val['photo_path'] && strpos($val['photo_path'],'http') === false){
                $list[$key]['photo_path'] = config('http_server').$val['photo_path'];
            }
            //职业
            if($val['zhiye']){
                $list[$key]['zhiye'] = $zhiyeModel->where('id',$val['zhiye'])->value('name');
            }else{
                $list[$key]['zhiye'] = '';
            }
            $list[$key]['is_order'] = 0;
            if($user_id > 0){
                if($orderModel->where('foreign_key',$val['id'])->where('apply_user',$user_id)->find()){
                    $list[$key]['is_order'] = 1;
                }
            }
            
        }

        return $list;
    }
}
